const Towxml = require('/towxml/main');
const util = require('/utils/util.js');
var interval;
var interval1;

App({
  onLaunch: function() {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function(res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function() {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function(res) {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              }
            });
          });
          updateManager.onUpdateFailed(function() {
            wx.showModal({
              title: '已经有新版本了哟~',
              content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
            });
          });
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法更好体验程序，请升级到最新微信版本后重试。'
      });
    }

    this.checkStatus();
    this.getUnreadMessage();
		this.getIntervalChat(this);
  },

	getIntervalChat: function (that) {
		interval1 = setInterval(function () {
			var loginInfo = wx.getStorageSync("loginInfo");
			if(loginInfo) {
				that.getFriendList();
			} else {
				console.log('用户尚未登录!');
			}
			
		}, 5000);
	},

	onHide: function() {
		clearInterval(interval);
		clearInterval(interval1);
	},

	getFriendList: function () {
		var that = this;

		wx.request({
			url: util.basePath + '/article/v1/getFriendList',
			method: "post",
			data: {
				account: wx.getStorageSync("loginInfo").account,
				app_sid: wx.getStorageSync("loginInfo").app_sid
			},
			header: {
				'content-type': 'application/json'
			},
			success(res) {
				if (res.data.status == 200) {
					var chat_count = 0;
					wx.setStorage({
						key: 'friendList',
						data: res.data.payload,
					});

					res.data.payload.forEach(friend => {
						chat_count += friend.chat_count;
					});

					if (chat_count > 0) {
						wx.setTabBarBadge({
							index: 2,
							text: String(chat_count)
						});
					} else {
						wx.removeTabBarBadge({
							index: 2,
						});
					}
				}
			}
		});
	},

  getUnreadMessage: function() {
    interval = setInterval(function() {
			var loginInfo = wx.getStorageSync("loginInfo");
			if(loginInfo) {
				//获取未读消息条数
				wx.request({
					url: util.basePath + '/article/v1/unreadCount',
					method: "post",
					data: {
						account: loginInfo.account,
						app_sid: loginInfo.app_sid,
						openid: loginInfo.openid
					},
					header: {
						'content-type': 'application/json'
					},
					success(res) {
						if (res.data.status == 200) {
							// console.log('成功获取到' + (res.data.payload.add_count + res.data.payload.comment_count + res.data.payload.stars_count) + '条未读消息!');
							wx.setStorage({
								key: 'unreadCount',
								data: res.data.payload.add_count + res.data.payload.comment_count + res.data.payload.stars_count
							});

							wx.setStorage({
								key: 'unreadMessage',
								data: res.data.payload
							});

							if (res.data.payload.add_count + res.data.payload.comment_count + res.data.payload.stars_count > 0) {
								wx.setTabBarBadge({
									index: 3,
									text: String(res.data.payload.add_count + res.data.payload.comment_count + res.data.payload.stars_count)
								});
							} else {
								wx.removeTabBarBadge({
									index: 3,
								});
							}
						}
					}
				});
			} else {
				console.log('用户尚未登录!');
			}
      
    }, 5000);
  },

  towxml: new Towxml(),

  globalData: {
    userInfo: {
      nickName: '请先登录',
      avatarUrl: '/images/defule.png'
    },
  },

  checkStatus: function() {
    var that = this;

    wx.request({
      url: util.basePath + '/article/v1/checkStatus',
      method: "post",
      data: {
        v: '1.0.8'
      },
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        if (res.data.status == 200) {
          wx.setStorage({
            key: 'checkStatus',
            data: true
          });
        } else {
          wx.setStorage({
            key: 'checkStatus',
            data: false
          });
        }
      }
    });
  },

  // 更新小程序
  updateManager: function() {
    //获取系统信息 客户端基础库
    wx.getSystemInfo({
      success: function(res) {
        //基础库版本比较，版本更新必须是1.9.90以上
        const v = util.compareVersion(res.SDKVersion, '1.9.90');
        if (v > 0) {
          const manager = wx.getUpdateManager();
          manager.onCheckForUpdate(function(res) {
            // 请求完新版本信息的回调
            //console.log(res.hasUpdate);
          });
          manager.onUpdateReady(function() {
            wx.showModal({
              title: '更新提示',
              content: '新版本已经准备好，是否重启应用？',
              success: function(res) {
                if (res.confirm) {
                  // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                  manager.applyUpdate();
                }
              }
            })
          });
          manager.onUpdateFailed(function() {
            // 新的版本下载失败
          });
        } else {
          wx.showModal({
            title: '温馨提示',
            content: '当前微信版本过低，无法更好体验程序，请升级到最新微信版本后重试。'
          });
        }
      },
    });
  }
});